package com.abc.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
 * @Author yaxiongliu
 * 目标：模拟登陆权限校验
 *
 **/
@Component
public class URLValidateFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求参数：token
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getQueryParams().getFirst("token");
        //2.判断token是否存在
        if (StringUtils.isEmpty(token)) {
        //2.1如果不存在，则拦截请求并且提示用户未授权错误
            ServerHttpResponse response = exchange.getResponse();
            //提示用户未授权错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//拦截当前请求
        }
        //2.2如果存在，则放行请求
        return chain.filter(exchange);
    }

    //过滤器有一个栈：
    @Override
    public int getOrder() {//返回值可以设置过滤器执行顺序
        return Integer.MAX_VALUE;//返回值越大执行顺序越靠前
    }
}
